<template>
  <el-container direction="vertical" class="container">
    <el-row>
      <el-col :span="24">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="用户名">
            <el-input v-model="searchForm.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
          </el-form-item>
          <el-button type="primary" icon="el-icon-circle-plus-outline" @click="dialogFormVisible=true;dialogTitle='新增用户'">新增用户</el-button>
        </el-form>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-table
          v-loading="listLoading"
          :data="tableData"
          border
          style="width: 100%;height: 568px;"
          max-height="568"
        >
          <!-- <el-table-column
            prop="_id"
            label="id"
            width="200"
            align="center"
          /> -->
          <el-table-column
            label="序号"
            type="index"
            width="50"
            align="center"
          />
          <el-table-column
            prop="username"
            label="用户名"
            width="200"
            align="center"
          />
          <el-table-column
            prop="role"
            label="角色"
            width="200"
            align="center"
          />
          <el-table-column
            prop="password"
            label="密码"
            width="300"
            align="center"
          />
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                size="medium"
                icon="el-icon-edit-outline"
                title="编辑"
                round
                @click="handleEdit(scope.$index, scope.row)"
              />
              <el-button
                v-if="currUser.indexOf(scope.row.role)===-1?true:false"
                size="medium"
                type="danger"
                title="删除"
                icon="el-icon-delete"
                round
                @click="handleDelete(scope.$index, scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :current-page="tableQuery.page"
          :page-size="tableQuery.pageSize"
          @current-change="handleCurrentChange"
          @prev-click="handleCurrentChange"
          @next-click="handleCurrentChange"
        />
      </el-col>
    </el-row>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      close-on-press-escape
      close-on-click-modal
      @close="cancel('AddForm')"
    >
      <el-form ref="AddForm" :model="AddForm" :rules="AddRules">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="AddForm.username" autocomplete="off" :disabled="dialogTitle==='编辑'?true:false" />
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="AddForm.password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="角色" :label-width="formLabelWidth" prop="role">
          <el-select v-model="AddForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin" />
            <el-option label="采购员" value="buyer" />
            <el-option label="收银员" value="cashier" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('AddForm')">取 消</el-button>
        <el-button type="primary" @click="submitForm('AddForm')">确 定</el-button>
      </div>
    </el-dialog>

  </el-container>

</template>

<script>
import { getInfo, delUser, addUser, updateUser } from '@/api/user'
import { getToken } from '@/utils/auth'
import { Message, MessageBox } from 'element-ui'
export default {
  name: 'UserSystem',
  data() {
    // const validatePassword = (rule, value, callback) => {
    //   if (value.length < 6) {
    //     callback(new Error('密码长度必须大于6位'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      searchForm: {
        username: ''
      },
      listLoading: true, // 列表加载动画
      currUser: this.$store.getters.roles, // 获取当前登录用户
      tableData: null, // 表格数据
      total: 0, // 表格总数
      isHidePage: false, // 是否隐藏分页
      tableQuery: { // 表格查询参数
        page: 1,
        pageSize: 10,
        name: '',
        token: getToken()
      },
      dialogFormVisible: false, // 对话框是否隐藏
      dialogTitle: '', // 对话框标题
      AddForm: { // 对话框表单数据
        username: '',
        password: '',
        role: ''
      },
      AddRules: { // 对话框表单验证
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'change' }],
        role: [{ required: true, message: '请选择角色', trigger: 'change' }]
      },
      formLabelWidth: '120px'
    }
  },
  created() {
    this.getTable()
  },
  methods: {
    onSubmit() {
      this.tableQuery.name = this.searchForm.username
      this.getTable()
    },
    getTable() {
      this.listLoading = true
      getInfo(this.tableQuery).then(response => {
        if (response) {
          if (this.tableQuery.name) {
            const arr = []
            arr.push(response.data.data)
            this.tableData = arr
            this.total = arr.length
          } else {
            this.tableData = response.data.list
            this.total = response.data.total
          }
          setTimeout(() => {
            this.listLoading = false
          }, 2 * 1000)
        }
        this.listLoading = false
      })
      if (this.total / this.tableQuery.pageSize <= 1) {
        this.isHidePage = true
      }
      // if(this.$store.getters.roles)
    },
    handleCurrentChange(val) {
      this.tableQuery.page = val
      this.getTable()
    },
    handlePreClick(val) {
      this.tableQuery.page = val
      this.getTable()
    },
    handleNextClick(val) {
      this.tableQuery.page = val
      this.getTable()
    },
    handleEdit(index, row) {
      this.dialogFormVisible = true
      this.dialogTitle = '编辑'
      this.AddForm = {
        username: row.username,
        password: row.password,
        role: row.role
      }
      // this.AddForm.username = row.username
      // this.AddForm.password = row.password
      // this.AddForm.role = row.role
    },
    handleDelete(index, row) {
      MessageBox.confirm('将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const payload = {}
        payload.username = row.username
        payload.option = 0
        delUser(payload).then(response => {
          Message({
            message: response.data.message,
            type: 'success',
            duration: 5 * 1000
          })
        })
        this.getTable()
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogTitle !== '编辑') {
            addUser(this.AddForm).then(res => {
              if (res) {
                Message({
                  message: res.data.message,
                  type: 'success',
                  duration: 5 * 1000
                })
                this.dialogFormVisible = false
                this.$refs[formName].resetFields()
              }
            })
            this.getTable()
          } else {
            updateUser(this.AddForm).then(res => {
              if (res) {
                Message({
                  message: res.data.message,
                  type: 'success',
                  duration: 5 * 1000
                })
                this.dialogFormVisible = false
                this.$refs[formName].resetFields()
              }
            })
            this.getTable()
          }
        } else {
          return false
        }
      })
    },
    cancel(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
      // this.AddForm = { // 对话框表单数据
      //   username: '',
      //   password: '',
      //   role: ''
      // }
    }
  }
}
</script>

<style lang="scss" scoped>
.container{
  height: 100%;
  padding: 10px;
}
</style>
